package com.zlh.elasticsearch;

import com.zlh.util.ElasticPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @package com.zlh.elasticsearch
 * @company: dacheng
 * @author: zlh
 * @createDate: 2021/4/12
 */
public class EsDateFormatDemo {
    public static void main(String[] args) throws IOException {
        ElasticPoolUtil elasticPoolUtil = new ElasticPoolUtil();
        RestHighLevelClient client = null;
        try {
            client = elasticPoolUtil.getClient();
            String index = "dc_date_test";
            Map<String,String> docMap = new HashMap<>();
            docMap.put("Time","2020-01-01 07:01:09");
            docMap.put("Pro_tools","RZY");
            IndexRequest indexRequest = new IndexRequest(index).source(docMap);

            Map<String,Object> docMap2 = new HashMap<>();
            docMap2.put("Time",new Date());
            docMap2.put("Pro_tools","LJ");
            // date format(yyyy-MM-dd HH:mm:ss)类型，不能插入Date类型，且Date类型插入少8小时，format后不存在少8小时问题
            IndexRequest indexRequest2 = new IndexRequest(index).source(docMap2);
            //插入
            client.index(indexRequest, RequestOptions.DEFAULT);

            //查询
            SearchRequest searchRequest = new SearchRequest("dc_date_test");
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit:hits) {
                System.out.println(hit.getSourceAsString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            elasticPoolUtil.returnClient(client);
        }
    }
}
